﻿using System;
using WeDonekRpc.CacheClient.Config;
using WeDonekRpc.Helper;
using StackExchange.Redis;
namespace WeDonekRpc.CacheClient.Redis
{
    internal class RedisHelper
    {
        private static RedisClient _RedisClient = null;
        private static RedisClient _PublicClient = null;

        internal static RedisClient PublicClient { get => _PublicClient; }
        internal static RedisClient RedisClient { get => _RedisClient; }

        public static bool InitCache (RedisConfig config)
        {
            if (config.ServerIp.IsNull())
            {
                return false;
            }
            RedisClient.Init(config);
            try
            {
                _RedisClient = new RedisClient();
                _PublicClient = new RedisClient(CommandMap.Default, "RedisPublic", true);
                return true;
            }
            catch (Exception e)
            {
                new ErrorLog(e, "Redis初始化失败!", "Redis")
                {
                    LogContent = config.ToJson()
                }.Save();
                return false;
            }
        }

        public static RedisClient GetNewClient (string name)
        {
            return new RedisClient(CommandMap.Default, name, false);
        }

        public static byte[] CacheLua (string lua)
        {
            IServer[] servers = _PublicClient.GetServers();
            byte[] hash = null;
            servers.ForEach(c =>
            {
                hash = c.ScriptLoad(lua);
            });
            return hash;
        }

        public static void Close ()
        {
            _RedisClient.Dispose();
            _PublicClient.Dispose();
        }
    }
}
